package com.awspaas.user.apps.cpq.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CPQ_GetAllComponentNumberWeb {

	public String getAllComponentNumber(UserContext userContext, String bindId, String cs, String datas) {
		Workbook workbookwl = new XSSFWorkbook();
		try {
			// 将数组转换为列表
			// JSONArray list=JSONObject.parseArray(cs);		
			//JSONArray mList=JSONObject.parseArray(datas);	
			List<BO> list=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG_PRICE_PARAMETERS").bindId(bindId).list();
			List<BO> mList=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG_GRID").bindId(bindId).list();
			// 获取模块所需参数信息
			Map<String, JSONObject> pMap = new HashMap<String, JSONObject>();
			Map<String, String> nameMap = new HashMap<String, String>();
			Map<String, String> noMap = new HashMap<>();
			for (int i = 0; i < list.size(); i++) {
				//JSONObject json = (JSONObject) list.get(i);
				BO json = list.get(i);
				String bh = (String) json.get("PARMENTIER_NO");
				String value = (String) json.get("PARMENTIER_VALUE");
				String name = (String) json.get("PARMENTIER_NAME");
				String dw = (String) json.get("DW");
				JSONObject jsonObject=new JSONObject();
				//判断value是否为数据
				if( NumberUtils.isCreatable(value)) {
					jsonObject.put("type", "1");//值为1者表示value为数值
				}else {
					jsonObject.put("type", "0");//值为0者表示value为字符串
				}
				jsonObject.put("value", value);
				pMap.put(bh, jsonObject);
				nameMap.put(bh, name);
				int num = i + 1;
				noMap.put(bh, "B$" + num);
			}
			System.out.println("pMap:"+pMap.toString());
			// 设置参数值到单元格中
			Sheet sheet = workbookwl.createSheet("Sheet1");
			for (int i = 0; i < list.size(); i++) {
				int num = i + 1;
				Cell cellB1 = sheet.createRow(i).createCell(1);
				//JSONObject jsonObject = (JSONObject) list.get(i);
				BO jsonObject =  list.get(i);
				String bh = (String) jsonObject.get("PARMENTIER_NO");
				JSONObject jsonObject2=	pMap.get(bh);
				String type=jsonObject2.getString("type");
				if(type.equals("0")) {
					cellB1.setCellValue(jsonObject2.getString("value"));
					System.out.println("cellB1:"+cellB1.getStringCellValue());
				}else {
					String value=jsonObject2.getString("value");
					double  numValue=Double.parseDouble(value);		
					 cellB1.setCellValue(numValue);
					 System.out.println("cellB1:"+cellB1.getNumericCellValue());
				}
			}
			List<BO> bos=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG_GRID").bindId(bindId).list();
			//存放已经保存的数据
			Map<String, BO> boMap = new HashMap<>();
			for (BO bo : bos) {
				boMap.put(bo.getString("ID"), bo);
			}
			//对模块中有计算公式的物料进行数量计算
			for (int i = 0; i < mList.size(); i++) {
				
				//JSONObject json = (JSONObject) mList.get(i);
				BO json =  mList.get(i);
				String equation = json.getString("WLJSGS");
				Document document = Jsoup.parse(equation);
				String newQuation=document.text();

				if (!newQuation.equals("0")&&!newQuation.isEmpty()) {						
					System.out.println("参数计算公式："+newQuation);
					// 获取物料数量计算公式中参数代号，如果有则将代号存放在list中
					for (String key : pMap.keySet()) {
						int num = newQuation.indexOf(key);
						if (num > -1) {
							newQuation = newQuation.replace(key, noMap.get(key));
						}
					}
					System.out.println("转换后的参数计算公式："+newQuation);
					// 计算出物料数量和当前模块的物料成本价格
					FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
					Cell cellB1 = sheet.createRow(list.size()+i).createCell(2);
					cellB1.setCellFormula(newQuation);
					formulaEvaluator.evaluateFormulaCell(cellB1);
					// 获取公式计算结果
					CellValue cellValue = formulaEvaluator.evaluate(cellB1);
					System.out.println("The result of the formula is: " + cellValue.getNumberValue());
					String price1 = json.getString("DJ").isEmpty()?"0":json.getString("DJ");						
					String clf1 = json.getString("CLF").isEmpty()?"0":json.getString("CLF");
					String rgf = json.getString("RGF").isEmpty()?"0":json.getString("RGF");	
					String wx = json.getString("WXWG").isEmpty()?"0":json.getString("WXWG");	
					String cgf = json.getString("CGF").isEmpty()?"0":json.getString("CGF");
					String tj = json.getString("TJ").isEmpty()?"0":json.getString("TJ");	
					String zl = json.getString("ZL").isEmpty()?"0":json.getString("ZL");	
					double total1 = Double.parseDouble(price1) * cellValue.getNumberValue();					
					double clfnum1 = Double.parseDouble(clf1) * cellValue.getNumberValue();					
					double rgfnum = Double.parseDouble(rgf) * cellValue.getNumberValue();
					double wxnum = Double.parseDouble(wx) * cellValue.getNumberValue();
					double cgfnum = Double.parseDouble(cgf) * cellValue.getNumberValue();
					double tjnum = Double.parseDouble(tj) * cellValue.getNumberValue();
					double zlnum = Double.parseDouble(zl) * cellValue.getNumberValue();
					
					// 将数量和成本价格放入物料map集合中
					if(boMap.containsKey(json.getString("ID"))) {
						BO bo=boMap.get(json.getString("ID"));
						bo.set("SL", cellValue.getNumberValue());
						bo.set("ZJ",total1);						
						bo.set("ZCGF",cgfnum);
						bo.set("ZGSF",rgfnum);
						bo.set("ZWX",wxnum);
						bo.set("ZCLF",clfnum1);						
						bo.set("ZTJ",tjnum);
						bo.set("ZZL",zlnum);
						SDK.getBOAPI().update("BO_EU_CPQ_MODULE_MSG_GRID", bo);
					}										                    
				}
			}
			ResponseObject ro = ResponseObject.newOkResponse();
			return ro.toString();
		} catch (Exception e) {
			throw  e;
		}finally {
			try {
				workbookwl.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		        
	}

}
